<?php


namespace app\admin\services\redis;


class RedisService
{

    protected static $handler = null;
    protected $options;

    public function __construct($options = [])
    {
        $options = [
            'host' => config('redis.host'),//ip
            'port' => 6379,
            'password' => config('redis.password'),//密码和ip用的配置,和这里无关
            'select' => 0,
            'timeout' => 0,//关闭时间 0:代表不关闭
            'expire' => 0,
            'persistent' => false,
            'prefix' => '',
        ];
        if (!extension_loaded('redis')) {   //判断是否有扩展(如果你的apache没reids扩展就会抛出这个异常)
            throw new \BadFunctionCallException('not support: redis');
        }
        $this->options = $options;
        $func = $this->options['persistent'] ? 'pconnect' : 'connect';     //判断是否长连接
        self::$handler = new \Redis();
        self::$handler->$func($this->options['host'], $this->options['port'], $this->options['timeout']);

        if ('' != config('redis.password')) {
            self::$handler->auth($this->options['password']);
        }

        if (0 != $this->options['select']) {
            self::$handler->select($this->options['select']);
        }
    }

    /**
     * 根据ID得到 hash 后 0～m-1 之间的值
     *
     * @param string $id
     * @param int $m
     * @return int
     */
    private static function _hashId($id, $m = 10)
    {
        //把字符串K转换为 0～m-1 之间的一个值作为对应记录的散列地址
        $k = md5($id);
        $l = strlen($k);
        $b = bin2hex($k);
        $h = 0;
        for ($i = 0; $i < $l; $i++) {
            //相加模式HASH
            $h += substr($b, $i * 2, 2);
        }
        $hash = ($h * 1) % $m;
        return $hash;
    }

    /**
     * 随机 HASH 得到 Redis Slave 服务器句柄
     *
     * @return redis object
     */
    private function _getSlaveRedis()
    {
        // 就一台 Slave 机直接返回
        if ($this->_sn <= 1) {
            return $this->_linkHandle['slave'][0];
        }
        // 随机 Hash 得到 Slave 的句柄
        $hash = $this->_hashId(mt_rand(), $this->_sn);
        return $this->_linkHandle['slave'][$hash];
    }

    /**
     * 写入缓存
     * @param string $key 键名
     * @param string $value 键值
     * @param int $exprie 过期时间 0:永不过期
     * @return bool
     */
    public static function set($key, $value, $exprie = 0)
    {
        if ($exprie == 0) {
            $set = self::$handler->set($key, $value);
        } else {
            $set = self::$handler->setex($key, $exprie, $value);
        }
        return $set;
    }

    /**
     * 读取缓存
     * @param string $key 键值
     * @return mixed
     */
    public static function get($key)
    {
        $fun = is_array($key) ? 'Mget' : 'get';
        return self::$handler->{$fun}($key);
    }

    /**
     * 获取值长度
     * @param string $key
     * @return int
     */
    public static function lLen($key)
    {
        return self::$handler->lLen($key);
    }

    /**
     * 将一个或多个值插入到列表头部
     * @param $key
     * @param $value
     * @return int
     */
    public static function LPush($key, $value, $value2 = null, $valueN = null)
    {
        return self::$handler->lPush($key, $value, $value2, $valueN);
    }

    /**
     * 移出并获取列表的第一个元素
     * @param string $key
     * @return string
     */
    public static function lPop($key)
    {
        return self::$handler->lPop($key);
    }

    public static function RPush($key, $value, $value2 = null, $valueN = null)
    {
        return self::$handler->rPush($key, $value, $value2, $valueN);
    }

    /**
     * lrange
     */
    public  function lrange($key, $start, $end)
    {
        return self::$handler->lrange($key, $start, $end);
    }

    /**
     *
     */
    public static function close()
    {
        return self::$handler->close();
    }

    /**
     *    set hash opeation
     */
    public static function hset($name, $key, $value)
    {
        if (is_array($value)) {
            return self::$handler->hset($name, $key, serialize($value));
        }
        return self::$handler->hset($name, $key, $value);
    }

    /**
     *    get hash opeation
     */
    public static function hget($name, $key = null, $serialize = true)
    {
        if ($key) {
            $row = self::$handler->hget($name, $key);
            if ($row && $serialize) {
                unserialize($row);
            }
            return $row;
        }
        return self::$handler->hgetAll($name);
    }

    /**
     *    delete hash opeation
     * 删除指定key中的指定字段
     */
    public static function hdel($name, $key = null)
    {
        if ($key) {
            return self::$handler->hdel($name, $key);
        }
        return self::$handler->hdel($name, null);
    }

    /**
     *    delete hash opeation
     *
     */
    public static function del($name)
    {
        return self::$handler->del($name);
    }


    /**
     * Transaction start
     */
    public static function multi()
    {
        return self::$handler->multi();
    }

    /**
     * Transaction send
     */

    public static function exec()
    {
        return self::$handler->exec();
    }

    /**
     * 添空当前数据库
     *
     * @return boolean
     */
    public static function clear()
    {
        return self::$handler->flushDB();
    }

    /**
     * 条件形式设置缓存，如果 key 不存时就设置，存在时设置失败
     *
     * @param string $key 缓存KEY
     * @param string $value 缓存值
     * @return boolean
     */
    public static function setnx($key, $value)
    {
        return self::$handler->setnx($key, $value);
    }

    /**
     * 删除缓存
     *
     * @param string || array $key 缓存KEY，支持单个健:"key1" 或多个健:array('key1','key2')
     * @return int 删除的健的数量
     */
    public static function remove($key)
    {
        // $key => "key1" || array('key1','key2')
        return self::$handler->delete($key);
    }

    /**
     * 值加加操作,类似 ++$i ,如果 key 不存在时自动设置为 0 后进行加加操作
     *
     * @param string $key 缓存KEY
     * @param int $default 操作时的默认值
     * @return int　操作后的值
     */
    public static function incr($key, $default = 1)
    {
        if ($default == 1) {
            return self::$handler->incr($key);
        } else {
            return self::$handler->incrBy($key, $default);
        }
    }

    /**
     * 值减减操作,类似 --$i ,如果 key 不存在时自动设置为 0 后进行减减操作
     *
     * @param string $key 缓存KEY
     * @param int $default 操作时的默认值
     * @return int　操作后的值
     */
    public static function decr($key, $default = 1)
    {
        if ($default == 1) {
            return self::$handler->decr($key, 0);
        } else {
            return self::$handler->decrBy($key, $default);
        }
    }

    public static function select($num = 0)
    {
        return self::$handler->select($num);
    }

    public static function sadd($key, $value)
    {
        return self::$handler->sAdd($key, $value);
    }

    public static function smembers($key)
    {
        return self::$handler->SMEMBERS($key);
    }

    public static function hmset($key, $array)
    {
        return self::$handler->hMSet($key, $array);
    }

    public static function hlen($key)
    {
        return self::$handler->HLEN($key);
    }

    public static function hkeys($key)
    {
        return self::$handler->hKeys($key);
    }

    public static function hvals($key)
    {
        return self::$handler->hVals($key);
    }

    public static function hmget($key, $value)
    {
        return self::$handler->hmget($key, $value);
    }

    public  function lpush1($key, $value)
    {
        return self::$handler->lPush($key, $value);
    }

    public static function exists($key)
    {
        return self::$handler->exists($key);
    }

    public static function zincrby($key,$score,$id)
    {
        return self::$handler->zIncrBy($key,$score,$id);
    }

    public static function zrevrange($key,$start,$end)
    {
        return self::$handler->zRevRange($key,$start,$end,true);
    }

    public static function zadd($key,$score,$id)
    {
        return self::$handler->zAdd($key,$score,$id);
    }

    public static function keys($key)
    {
        return self::$handler->keys($key);
    }

}